﻿using System;
using System.Windows;
using DataBaseLibrary.DBInterfaces;
using DataBaseLibrary.DBObjectsFB;
using DocMreoLiteVersion.Reports.DeclarationReport;
using DocMreoLiteVersion.Reports.Pts;
using DocMreoLiteVersion.Reports.SaleContractReport;
using DocMreoLiteVersion.Reports;
using Application = System.Windows.Application;

namespace DocMreoLiteVersion
{
    public partial class MainWindow
    {

        private FormChoiseDocument _choiseDocument = null;
        
        /// <summary>
        /// Удаление контролов из грида
        /// </summary>
        private void DeleteUserControlFromGrid(IDBObject dbObject)
        {
            m_DetailGrid.Children.Clear();
            DocumentSelectMenu.IsEnabled = true;
            if (_choiseDocument == null)
            {
                _choiseDocument = new FormChoiseDocument();

                /*
                 * 
                 * Привязка событий нажатия кнопочек в choise_document к обработчикам
                 * от пунктов меню
                 * 
                 */
                _choiseDocument.CreateHistoryDocuments += _choiseDocument_CreateHistoryDocuments;
                _choiseDocument.SearchDocFromNumber += _choiseDocument_SearchDocFromNumber;
                _choiseDocument.DocumentOpenEvent += _choiseDocument_DocumentOpenEvent;
                //**********************************************************************

            }

            m_DetailGrid.Children.Add(_choiseDocument);

            if (dbObject == null) return;

            _choiseDocument.AddDbObjectListBox(dbObject);
        }



        private void _choiseDocument_DocumentOpenEvent(object sender, RoutedEventArgs e)
        {
            String numDocument = (e as RoutedEventSearchDocArgs).NumberDocument;
            SalesContract contract = new SalesContract();
            DataBaseLibrary.DBObjectsFB.Application declaration = new DataBaseLibrary.DBObjectsFB.Application();
            ApplicationVu vu = new ApplicationVu();

            try
            {
                db_provider.Load(contract, numDocument);
            }
            catch
            {
            }
            try
            {
                db_provider.Load(declaration, numDocument);
            }
            catch
            {
            }
            try
            {
                db_provider.Load(vu, numDocument);
            }
            catch
            {
            }

            if (contract.NumberSalesContract.Equals(numDocument))
            {
                var _contractReport = new Reports.SaleContractReport.FormSalesContract(db_provider, numDocument);
                _contractReport.CloseFormSalesContract += f_contract_CloseFormContracts;
                AddUserControlToGrid(_contractReport);
            }
            else
            {
                if (declaration.NumberDeclarationContract.Equals(numDocument))
                {
                    var _declarationReport = new Reports.DeclarationReport.FormDeclarationReport(db_provider, numDocument);
                    _declarationReport.CloseFormDeclaration += f_contract_CloseFormContracts;
                    AddUserControlToGrid(_declarationReport);
                }
                else
                {
                    if (vu.NumberApplication.Equals(numDocument))
                    {
                        Reports.DrivingLicenseReport.DrivingLicenseControl _declarationVuReport = new Reports.DrivingLicenseReport.DrivingLicenseControl(db_provider, numDocument);
                        _declarationVuReport.CloseFormDeclarationVu += f_contract_CloseFormContracts;
                        AddUserControlToGrid(_declarationVuReport);

                    }
                }
            }


        }



        /// <summary>
        /// Поиск документов для таблицы ранее созданных договоров
        /// </summary>
        void _choiseDocument_SearchDocFromNumber(object sender, RoutedEventArgs e)
        {
            RoutedEventSearchDocArgs args = e as RoutedEventSearchDocArgs;
            
            SalesContract contract = new SalesContract();
            DataBaseLibrary.DBObjectsFB.Application declaration = new DataBaseLibrary.DBObjectsFB.Application();
            ApplicationVu vu = new ApplicationVu();

            try { db_provider.Load(contract, args.NumberDocument); } catch{ }
            try { db_provider.Load(declaration, args.NumberDocument); } catch { }
            try { db_provider.Load(vu, args.NumberDocument); } catch { }

            if (contract.NumberSalesContract.Equals(args.NumberDocument))
            {
                try
                {
                    _choiseDocument.AddDbObjectListBox(contract);
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message);
                }
            }
            else
            {
                if (declaration.NumberDeclarationContract.Equals(args.NumberDocument))
                {
                    try
                    {
                        _choiseDocument.AddDbObjectListBox(declaration);
                    }
                    catch (Exception err)
                    {
                        MessageBox.Show(err.Message);
                    }
                }
                else
                {
                    if (vu.NumberApplication.Equals(args.NumberDocument))
                    {
                        try
                        {
                            _choiseDocument.AddDbObjectListBox(vu);
                        }
                        catch (Exception err)
                        {
                            MessageBox.Show(err.Message);
                        }
                        
                    }
                    else
                    {
                        MessageBox.Show("Ниодного документа с таким номером не найдено");
                    }
                }
            }
        }





        /// <summary>
        /// Показывает историю создания/изменения договоров
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _choiseDocument_CreateHistoryDocuments(object sender, RoutedEventArgs e)
        {
            IDBLogic logic = new FDBLogic(db_provider);
            IDBLogic.ResultFields resFields = logic.GetDocumentsHistory(session.user, DateTime.Now, DateTime.Now);


            ViewHistoryDocForm tableDlg = new ViewHistoryDocForm(db_provider, session.user);
            tableDlg.Owner = Application.Current.MainWindow;
            tableDlg.ShowDialog();
        }


        /// <summary>
        /// Добавление контролов в грид
        /// </summary>
        private void AddUserControlToGrid(UIElement element)
        {
            m_DetailGrid.Children.Clear();
            m_DetailGrid.Children.Add(element);
            DocumentSelectMenu.IsEnabled = false;
        }

        
        /// <summary>
        /// Событие выхода из формы
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void f_contract_CloseFormContracts(object sender, RoutedEventArgs e)
        {
            var routedEventCreateDeclarationArgs = e as RoutedEventCreateDeclarationArgs;
            if (routedEventCreateDeclarationArgs != null)
                DeleteUserControlFromGrid(routedEventCreateDeclarationArgs.ObjectContract);
        }


        //================================== События для Договора купли-продажи =============================================

        /// <summary>
        /// Создать новый договор купли-продажи
        /// </summary>
        private void CreatedNewSalesContract(object sender, RoutedEventArgs e)
        {
            FormSalesContract salesContract = new FormSalesContract(db_provider);
            salesContract.CloseFormSalesContract += f_contract_CloseFormContracts;
            AddUserControlToGrid(salesContract);
        }


        /// <summary>
        /// Найти договор по номеру
        /// </summary>
        private void FindNumberSalesContract(object sender, RoutedEventArgs e)
        {
            
            InputStringDlg dlg = new InputStringDlg();
            dlg.Owner = Application.Current.MainWindow;
            dlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            if (dlg.ShowDialog() ?? true)
            {
                if (dlg.ReturnString == String.Empty)
                {
                    MessageBox.Show("Вы не ввели номер договора!");
                    return;
                }
                String DocumentNumber = dlg.ReturnString;

                FormSalesContract salesContract = new FormSalesContract(db_provider, DocumentNumber);
                salesContract.CloseFormSalesContract += f_contract_CloseFormContracts;
                AddUserControlToGrid(salesContract);
            }
        }



        private void FindSalesContractClick(object sender, RoutedEventArgs e)
        {
            IDBLogic logic = new FDBLogic(db_provider);
            Individual individual = new Individual();
            
            IndividualInputData inputDataDlg = new IndividualInputData(individual);
            inputDataDlg.Owner = Application.Current.MainWindow;
            IDBLogic.ResultFields result;
            if (inputDataDlg.ShowDialog() ?? true)
            {
                result = logic.SearchSalesContract(individual);
            }
            else
            {
                return;
            }

            SearchResultTable tableDlg = new SearchResultTable(result);
            tableDlg.Owner = Application.Current.MainWindow;
            if (tableDlg.ShowDialog() ?? true)
            {
                FormSalesContract salesContract = new FormSalesContract(db_provider, (String)tableDlg.ReturnObject);
                salesContract.CloseFormSalesContract += f_contract_CloseFormContracts;
                AddUserControlToGrid(salesContract);
            }
        }



        private void ViewAllSalesContract(object sender, RoutedEventArgs e)
        {
            IDBLogic logic = new FDBLogic(db_provider);
            IDBLogic.ResultFields result = logic.SearchSalesContract(null);
            SearchResultTable tableDlg = new SearchResultTable(result);
            tableDlg.Owner = Application.Current.MainWindow;
            if (tableDlg.ShowDialog() ?? true)
            {
                FormSalesContract salesContract = new FormSalesContract(db_provider, (String)tableDlg.ReturnObject);
                salesContract.CloseFormSalesContract += f_contract_CloseFormContracts;
                AddUserControlToGrid(salesContract);
            }
        }




        //================================== События для заявления =========================================================

        /// <summary>
        /// Создать новое заявление
        /// </summary>
        private void CreateDeclNew(object sender, RoutedEventArgs e)
        {
            FormDeclarationReport _declarationReport = new FormDeclarationReport(db_provider);
            _declarationReport.CloseFormDeclaration += f_contract_CloseFormContracts;
            AddUserControlToGrid(_declarationReport);
        }




        /// <summary>
        /// Создать заявление на продавца
        /// </summary>
        private void CreateDeclFromSalesContrSaler(object sender, RoutedEventArgs e)
        {
            try
            {

                var salesContract = _choiseDocument.GetDbObjectFromListBox() as SalesContract;
                if (salesContract == null)
                {
                    MessageBox.Show("Документ не выбран или выбранный документ не является договором купли-продажи!");
                    return;
                }

                FormDeclarationReport _declarationReport = new FormDeclarationReport(db_provider,
                    salesContract.Saler.m_Individual, salesContract.RepresentativeSaler, salesContract.Vehicle);
                _declarationReport.CloseFormDeclaration += f_contract_CloseFormContracts;
                AddUserControlToGrid(_declarationReport);
            }
            catch (SystemException errorException)
            {
                MessageBox.Show(errorException.Message);
            }
        }

        /// <summary>
        /// Создать заявление на покупателя
        /// </summary>
        private void CreateDeclFromSalesContrBuyer(object sender, RoutedEventArgs e)
        {
            try
            {

                var salesContract = _choiseDocument.GetDbObjectFromListBox() as SalesContract;
                if (salesContract == null)
                {
                    MessageBox.Show("Документ не выбран или выбранный документ не является договором купли-продажи!");
                    return;
                }

                FormDeclarationReport _declarationReport = new FormDeclarationReport(db_provider,
                    salesContract.Buyer.m_Individual, salesContract.RepresentativeBuyer, salesContract.Vehicle);
                _declarationReport.CloseFormDeclaration += f_contract_CloseFormContracts;
                AddUserControlToGrid(_declarationReport);
            }
            catch (SystemException errorException)
            {
                MessageBox.Show(errorException.Message);
            }
        }


        /// <summary>
        /// Найти заявление по номеру
        /// </summary>
        private void FindNumberDeclaration(object sender, RoutedEventArgs e)
        {

            InputStringDlg dlg = new InputStringDlg();
            dlg.Owner = Application.Current.MainWindow;
            dlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            if (dlg.ShowDialog() ?? true)
            {
                if (dlg.ReturnString == String.Empty)
                {
                    MessageBox.Show("Вы не ввели номер заявления!");
                    return;
                }
                String DocumentNumber = dlg.ReturnString;

                FormDeclarationReport _declarationReport = new FormDeclarationReport(db_provider, DocumentNumber);
                _declarationReport.CloseFormDeclaration += f_contract_CloseFormContracts;
                AddUserControlToGrid(_declarationReport);
            }
        }

        /// <summary>
        /// Поиск по фио
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SearchApplicationClick(object sender, RoutedEventArgs e)
        {
            IDBLogic logic = new FDBLogic(db_provider);
            Individual individual = new Individual();

            IndividualInputData inputDataDlg = new IndividualInputData(individual);
            inputDataDlg.Owner = Application.Current.MainWindow;
            IDBLogic.ResultFields result;
            if (inputDataDlg.ShowDialog() ?? true)
            {
                result = logic.SearchDeclaration(individual);
            }
            else
            {
                return;
            }

            SearchResultTable tableDlg = new SearchResultTable(result);
            tableDlg.Owner = Application.Current.MainWindow;
            if (tableDlg.ShowDialog() ?? true)
            {
                FormDeclarationReport _declarationReport = new FormDeclarationReport(db_provider, (string)tableDlg.ReturnObject);
                _declarationReport.CloseFormDeclaration += f_contract_CloseFormContracts;
                AddUserControlToGrid(_declarationReport);
            }
        }

        /// <summary>
        /// Вывод всех заявлений
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ViewAllApplications(object sender, RoutedEventArgs e)
        {
            IDBLogic logic = new FDBLogic(db_provider);
            IDBLogic.ResultFields result = logic.SearchDeclaration(null);
            SearchResultTable tableDlg = new SearchResultTable(result);
            tableDlg.Owner = Application.Current.MainWindow;
            if (tableDlg.ShowDialog() ?? true)
            {
                FormDeclarationReport _declarationReport = new FormDeclarationReport(db_provider, (string)tableDlg.ReturnObject);
                _declarationReport.CloseFormDeclaration += f_contract_CloseFormContracts;
                AddUserControlToGrid(_declarationReport);
            }
        }


        //================================== События для заявления на ВУ =========================================================


        /// <summary>
        /// Создать новое заявление на ВУ
        /// </summary>
        private void CreateDeclVuNew(object sender, RoutedEventArgs e)
        {
            Reports.DrivingLicenseReport.DrivingLicenseControl _declarationVuReport = new Reports.DrivingLicenseReport.DrivingLicenseControl(db_provider);
            _declarationVuReport.CloseFormDeclarationVu += f_contract_CloseFormContracts;
            
            AddUserControlToGrid(_declarationVuReport);
        }


        /// <summary>
        /// Создать заявление ВУ на продавца
        /// </summary>
        private void CreateDeclVuFromSalesContrSaler(object sender, RoutedEventArgs e)
        {
            try
            {

                var salesContract = _choiseDocument.GetDbObjectFromListBox() as SalesContract;
                if (salesContract == null)
                {
                    MessageBox.Show("Документ не выбран или выбранный документ не является договором купли-продажи!");
                    return;
                }
                Reports.DrivingLicenseReport.DrivingLicenseControl _declarationVuReport = new Reports.DrivingLicenseReport.DrivingLicenseControl(db_provider, salesContract.Saler.m_Individual);
                _declarationVuReport.CloseFormDeclarationVu += f_contract_CloseFormContracts;
                AddUserControlToGrid(_declarationVuReport);
            }
            catch (SystemException errorException)
            {
                MessageBox.Show(errorException.Message);
            }
        }

        /// <summary>
        /// Создать заявление на покупателя / заявителя
        /// </summary>
        private void CreateDeclVuFromSalesContrBuyer(object sender, RoutedEventArgs e)
        {
            try
            {

                var salesContract = _choiseDocument.GetDbObjectFromListBox() as SalesContract;
                Individual individual;
                if (salesContract != null)
                {
                    individual = salesContract.Buyer.m_Individual;
                }
                else
                {
                    var declaration = _choiseDocument.GetDbObjectFromListBox() as DataBaseLibrary.DBObjectsFB.Application;
                    if (declaration != null)
                    {
                        individual = declaration.Owner;
                    }
                    else
                    {
                        MessageBox.Show("Документ не выбран или выбранный документ не является договором купли-продажи или заявлением!");
                        return;
                    }
                }

                Reports.DrivingLicenseReport.DrivingLicenseControl _declarationVuReport = new Reports.DrivingLicenseReport.DrivingLicenseControl(db_provider, individual);
                _declarationVuReport.CloseFormDeclarationVu += f_contract_CloseFormContracts;
                AddUserControlToGrid(_declarationVuReport);
            }
            catch (SystemException errorException)
            {
                MessageBox.Show(errorException.Message);
            }
        }



        /// <summary>
        /// Найти заявление ВУ по номеру
        /// </summary>
        private void FindNumberDeclarationVu(object sender, RoutedEventArgs e)
        {

            InputStringDlg dlg = new InputStringDlg();
            dlg.Owner = Application.Current.MainWindow;
            dlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            if (dlg.ShowDialog() ?? true)
            {
                if (dlg.ReturnString == String.Empty)
                {
                    MessageBox.Show("Вы не ввели номер заявления!");
                    return;
                }
                String DocumentNumber = dlg.ReturnString;

                Reports.DrivingLicenseReport.DrivingLicenseControl _declarationVuReport = new Reports.DrivingLicenseReport.DrivingLicenseControl(db_provider, DocumentNumber);
                _declarationVuReport.CloseFormDeclarationVu += f_contract_CloseFormContracts;
                AddUserControlToGrid(_declarationVuReport);
            }
        }


        /// <summary>
        /// Поиск по ФИО
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SearchAppliationVu(object sender, RoutedEventArgs e)
        {
            IDBLogic logic = new FDBLogic(db_provider);
            Individual individual = new Individual();

            IndividualInputData inputDataDlg = new IndividualInputData(individual);
            inputDataDlg.Owner = Application.Current.MainWindow;
            IDBLogic.ResultFields result;
            if (inputDataDlg.ShowDialog() ?? true)
            {
                result = logic.SearchDeclarationVu(individual);
            }
            else
            {
                return;
            }

            SearchResultTable tableDlg = new SearchResultTable(result);
            tableDlg.Owner = Application.Current.MainWindow;
            if (tableDlg.ShowDialog() ?? true)
            {
                Reports.DrivingLicenseReport.DrivingLicenseControl _declarationVuReport = new Reports.DrivingLicenseReport.DrivingLicenseControl(db_provider, (string)tableDlg.ReturnObject );
                _declarationVuReport.CloseFormDeclarationVu += f_contract_CloseFormContracts;
                AddUserControlToGrid(_declarationVuReport);
            }
        }

        /// <summary>
        /// Вывести все заявления
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ViewAllApplicationsVu(object sender, RoutedEventArgs e)
        {
            IDBLogic logic = new FDBLogic(db_provider);
            IDBLogic.ResultFields result = logic.SearchDeclarationVu(null);
            SearchResultTable tableDlg = new SearchResultTable(result);
            tableDlg.Owner = Application.Current.MainWindow;
            if (tableDlg.ShowDialog() ?? true)
            {
                Reports.DrivingLicenseReport.DrivingLicenseControl _declarationVuReport = new Reports.DrivingLicenseReport.DrivingLicenseControl(db_provider, (string)tableDlg.ReturnObject);
                _declarationVuReport.CloseFormDeclarationVu += f_contract_CloseFormContracts;
                AddUserControlToGrid(_declarationVuReport);
            }
        }

        //================================== События для печати в ПТС =========================================================

        /// <summary>
        /// Печать в ПТС
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PrintPts(object sender, RoutedEventArgs e)
        {
            try
            {
                SalesContract contract = _choiseDocument.GetDbObjectFromListBox() as SalesContract;
                if (contract == null)
                {
                    MessageBox.Show("Документ не выбран или выбранный документ не является договором купли-продажи!");
                }
                PtsPreview ptsPreview = new PtsPreview(contract);
                ptsPreview.ClosePtsForm += f_contract_CloseFormContracts;
                AddUserControlToGrid(ptsPreview);
            }
            catch (SystemException err)
            {
                MessageBox.Show(err.Message);
            }
        }



        //========================================= События, не относящиеся к документам ========================================

        private void Window_Closed_1(object sender, EventArgs e)
        {
            if (db_provider != null)
                db_provider.CloseConnect();            
        }


        private void SettingApplicationItem(object sender, RoutedEventArgs e)
        {
            SettingWindow setting = new SettingWindow(db_provider);
            setting.Owner = this;
            setting.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            setting.ShowDialog();
        }

        private void About_Click(object sender, RoutedEventArgs e)
        {
            AboutWindow about_window = new AboutWindow();
            about_window.Owner = this;
            //about_window. Переместить в центр
            about_window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            about_window.ShowDialog();
        }

        /// <summary>
        /// Закрывает главное окно приложения
        /// </summary>
        private void ExitItem_OnClick(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

    }
}
